/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.grnt.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class give some static common functions as utilities.
 * @author sayid
 */
public class CommonFunc {
	/**
	 * This method format a "select" command string. The generic select command
	 * string mybe has some information that will be provide in future. These
	 * information is template by char '?'.
	 * @param qryStr This parameter is a "select" command string. But it has
	 * some chars "?" represent parameters in the command and the parameters 
	 * will be insted in future.
	 * @param strs The list of strings will be used to insted the char '?' in
	 * the qryStr parameter.
	 * @return A "select" string which is qryStr after insted '?' by parmeter
	 * strs.
	 */
	public static String sqlStrFormat(String qryStr, String ... strs) {
		StringBuffer sb = new StringBuffer();
		Pattern p = Pattern.compile("[?]|[&][?]");
		Matcher m = p.matcher(qryStr);
		int i = 0, strCount = strs.length;
		while(m.find()) {
			if ((m.start() < qryStr.length())&&(qryStr.charAt(m.start()) == '&')) {
				m.appendReplacement(sb, "?");
				continue;
			}
			if ((i < strCount) && (strs[i] != null)) {
				m.appendReplacement(sb, strs[i]);
			}
			else
				m.appendReplacement(sb, "NULL");
			i++;
		}
		m.appendTail(sb);
		return sb.toString();
	}

	/**
	 *
	 * Insteads "'NULL'" in the string with "NULL". That means remove charactor '
	 * around "NULL".
	 * @param qryStr The "select" command string, whitch mybe has substring 'NULL'
	 * @return Return a string which seem to input parameter qryStr but translate
	 * substring 'NULL' to NULL .
	 */
	public static String sqlNullStr2NullVal(String qryStr) {
		Pattern p = Pattern.compile("'NULL'", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(qryStr);
		return m.replaceAll("NULL");
	}
}